﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.Unity;
using System.Reflection;
using System.IO;

namespace HanGu.CRM
{
    public class ServiceFactory
    {
       static IUnityContainer container = new UnityContainer();
       static string filePath = string.Empty;
        static ServiceFactory()
        {
            filePath = AppDomain.CurrentDomain.BaseDirectory;
            Register(LoadService(),LoadServiceInterface());
        }
        public ServiceFactory() { }

        static Assembly LoadService()
        {
            return Assembly.LoadFile(Directory.GetFiles(filePath + "\\bin", "*.Services.dll").FirstOrDefault());           
        }

        static Assembly LoadServiceInterface()
        {
            return Assembly.LoadFile(Directory.GetFiles(filePath + "\\bin", "*.Services.Interface.dll").FirstOrDefault());
        }

       static void Register(Assembly service,Assembly _interface)
        {
            foreach (var item in service.GetTypes())
            {
               //var serviceInterface= _interface.GetTypes().SingleOrDefault(c=>c.Name.IndexOf(item.Name)>=0);
                var interfaces = item.GetInterfaces();
                bool isMutile = interfaces.Length > 1;

                foreach (var inter in interfaces)
                {
                    if (isMutile)
                    {
                        container.RegisterType(inter, item, inter.Name);
                    }
                    else
                    { container.RegisterType(inter, item); }
                }
               
            }
        }

        public static T GetService<T>() where T:class
        {
            return container.Resolve<T>();        
        }
    }
}